package com.gofun.framework.dubbo.core.environment;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.StandardServletEnvironment;

import com.gofun.framework.dubbo.core.environment.config.IntegrationConfigEnum;

/**
 * @Project       : framework-dubbo-provider
 * @Program Name  : com.ljt.framework.dubbo.provider.EnvironmentConfiguration.java
 * @Description   : Dubbo相关环境属性配置
 * @Author        : wangchao
 * @Creation Date : 2016年5月18日 下午5:36:52 
 * @ModificationHistory  
 * Who          When             What 
 * ----------   -------------    -----------------------------------
 * wangchao     2016年5月18日        create
 */
@Component
public class EnvironmentConfiguration implements BeanFactoryPostProcessor,EnvironmentAware {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	private boolean process = false;
	
	@Override
	public void setEnvironment(Environment env) {
        processEnvironment(env);
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		processEnvironment(beanFactory.getBean(StandardServletEnvironment.class));
	}
	
	/**
	 *  @Description	: 将环境变量中的dubbo配置加入全局变量
	 *  @return         : void
	 *  @Creation Date  : 2016年5月19日 下午3:54:59 
	 *  @Author         : wangchao
	 */
	private void processEnvironment(Environment env){
		if(process)
			return;
		logger.info("dubbo environment begin……");
        logger.info("profiles.activated：" + env.getProperty("spring.profiles"));
        // 遍历集成配置，获取有效值设置为系统属性
        for (IntegrationConfigEnum config : IntegrationConfigEnum.values()) {
        	for (ConfigMapping property : config.mappings) {
        		property.getResolveMapping().parse(env, property);
        	}
		}
        logger.info("dubbo environment end……");
        this.process = true;
	}

}
